// https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
// 19. 删除链表的倒数第 N 个节点
// 给你一个链表，删除链表的倒数第 n 个节点，并且返回链表的头节点
import { ListNode } from '../utils/index.ts';

function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
    let dummy = new ListNode(0, head);
    let first = head;
    let second: ListNode | null = dummy;

    for (let i = 0; i < n; i++) {
        first = first && first.next;
    }

    while (first !== null) {
        first = first.next;
        second = second && second.next;
    }

    if (second && second.next) {
        second.next = second.next.next;
    }

    return dummy.next;
}
